package network.udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    DatagramSocket socket;
    String serverIp;
    int serverPort;

    public UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();//不能指定端口号，防止冲突
        serverIp = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端，启动！");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //输入请求
            System.out.println("输入请求");
            System.out.print(">> ");
            String request = scanner.nextLine();
            //发送请求
            System.out.println("发送请求");
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //接收响应
            System.out.println("接收响应");
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //解析响应
            System.out.println("解析响应");
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //处理响应
            System.out.println("处理响应");
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        //UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9091);
        UdpEchoClient client = new UdpEchoClient("62.234.27.59", 9091);
        client.start();
    }
}
